package com.lxm.framework.mongo;

import com.lxm.framework.mongo.core.MongoHelper;
import com.lxm.framework.mongo.core.MongoService;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.*;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

/**
 * @Author: Lys
 * @Date 2022/6/17
 * @Describe
 **/
@ConditionalOnProperty(prefix = "spring.data.mongodb", name = "database", havingValue = "true")
@Configuration
public class MongoConfig {

    @Autowired(required = false)
    public void mongoTemplate(@NonNull MongoTemplate mongoTemplate) {
        MongoHelper.mgt = mongoTemplate;
    }

    @Bean
    @Autowired(required = false)
    public MappingMongoConverter mappingMongoConverter(@NonNull MongoDatabaseFactory databaseFactory,@NonNull MongoCustomConversions customConversions,@NonNull MongoMappingContext mappingContext) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(databaseFactory);
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mappingContext);
        converter.setCustomConversions(customConversions);
        converter.setCodecRegistryProvider(databaseFactory);
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return converter;
    }

    @Bean
    @DependsOn("mappingMongoConverter")
    public MongoService mongoService() {
        return new MongoService();
    }
}
